package com.qyhl.module_practice.activity.detail.comment;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.module_practice.R;
import com.qyhl.module_practice.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeCommentBean;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeVolunteerBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.PRACTICE_COMMENT)
public class PracticeActCommentActivity extends BaseActivity implements PracticeActCommentContract.PracticeActCommentView {
    @BindView(R2.id.toolbar)
    Toolbar toolbar;
    @BindView(R2.id.commit_btn)
    TextView commitBtn;
    @BindView(R2.id.comment_content)
    EditText commentContent;
    @BindView(R2.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;

    private String actId;

    private PracticeActCommentPresenter mPresenter;

    private CommonAdapter commonAdapter;

    private int page = 1;

    private List<PracticeCommentBean> mDataList = new ArrayList<>();

    private PracticeCommentBean indexBean;

    private String message;

    private String userName;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getContentView() {
        return R.layout.practice_activity_comment;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new PracticeActCommentPresenter(this);
        actId = getIntent().getStringExtra("id");
        initView();
        setListenter();
        mPresenter.getCommentList(actId, page + "");
    }

    @Override
    protected void setListener() {

    }

    private void initView() {
        loadMask.setStatus(LoadingLayout.Loading);
        setSupportActionBar(toolbar);
        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setEnableLoadMore(true);

        recycleView.setLayoutManager(new LinearLayoutManager(this));

        recycleView.setAdapter(commonAdapter = new CommonAdapter<PracticeCommentBean>(this, R.layout.practice_item_comment, mDataList) {
            @Override
            protected void convert(ViewHolder holder, PracticeCommentBean bean, int position) {
                holder.setText(R.id.nickName, bean.getNickName());
                holder.setText(R.id.content, bean.getContent());
                holder.setText(R.id.publish_date, DateUtils.mTranslateDate(bean.getCreateDate()));
                ImageView headIcon = holder.getView(R.id.head_icon);

                Glide.with(getApplicationContext())
                        .load(bean.getLogo())
                        .apply(new RequestOptions().error(R.drawable.comment_head_default).placeholder(R.drawable.comment_head_default).circleCrop())
                        .into(headIcon);
            }

        });

    }


    private void setListenter() {
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                mPresenter.getCommentList(actId, page + "");
            }
        });

        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getCommentList(actId, page + "");
            }
        });

        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                page = 1;
                mPresenter.getCommentList(actId, page + "");
            }
        });

        commentContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (StringUtils.isNotEmpty(s.toString())) {
                    commitBtn.setEnabled(true);
                } else {
                    commitBtn.setEnabled(false);
                }
            }
        });
    }

    @Override
    public void commentError(String msg) {
        showToast(msg, 4);
    }

    @Override
    public void commentSuccess(String msg) {
        loadMask.setStatus(LoadingLayout.Success);
        showToast(msg, 4);
        commentContent.setText("");
        if (indexBean != null) {
            mDataList.add(0, indexBean);
            commonAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void setCommentList(List<PracticeCommentBean> beanList, boolean isMore) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        if (!isMore) {
            refresh.finishRefresh();
            mDataList.clear();
        } else {
            refresh.finishLoadMore();
        }
        mDataList.addAll(beanList);
        page++;
        commonAdapter.notifyDataSetChanged();
    }

    @Override
    public void setCommentError(String msg, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refresh.finishLoadMore();
            showToast(msg, 4);
        } else {
            loadMask.setStatus(LoadingLayout.Error);
            refresh.finishRefresh();
            if (!NetUtil.isNetworkAvalible(this)) {
                loadMask.setErrorImage(R.drawable.error_network);
                loadMask.setErrorText("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                loadMask.setErrorImage(R.drawable.empty_content);
                loadMask.setErrorText("暂无任何评论！");
            } else {
                loadMask.setErrorImage(R.drawable.error_content);
                loadMask.setErrorText(msg);
            }
        }
    }

    @Override
    public void setVolInfo(PracticeVolunteerBean bean) {
        String headIcon;
        String nickName;
        if (bean == null) {
            nickName = CommonUtils.getInstance().getNickName();
            headIcon = CommonUtils.getInstance().getUserLogo();
        } else {
            nickName = bean.getName();
            headIcon = bean.getLogo();
        }

        indexBean = new PracticeCommentBean(message, userName, DateUtils.getCurrentTime(), nickName, headIcon);
        mPresenter.addComment(actId, userName, message);
        hideInput();
    }

    @OnClick(R2.id.commit_btn)
    public void onViewClicked() {

        CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
            @Override
            public void login(boolean isLogin) {
                if (isLogin) {
                    message = commentContent.getText().toString();
                    if (StringUtils.isEmpty(message)) {
                        showToast("内容不能为空！", 4);
                        return;
                    }
                    userName = CommonUtils.getInstance().getUserName();

                    mPresenter.getVolInfo(userName);
                } else {
                    RouterManager.routerLogin(PracticeActCommentActivity.this, 0);
                }
            }

            @Override
            public void error(String s) {

            }
        });


    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BusFactory.getBus().post(new Event.PracticeActRefresh(0));
    }

    @Override
    protected void onResume() {
        super.onResume();
        ActionLogUtils.getInstance().onResume(this, ActionConstant.PRACTICE_COMMENT);
    }

    @Override
    protected void onPause() {
        super.onPause();
        ActionLogUtils.getInstance().onPause(this, ActionConstant.PRACTICE_COMMENT);
    }


}
